package com.daniel.listener;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by daniel on 2015/7/15.
 */
public class DataSource<F> {
    Set<Listener<F>> listeners = new HashSet<>();

    public int getCount() {
        return listeners.size();
    }

    protected void beforeListenerAdded(com.daniel.listener.Listener<F> Listener) {

    }

    protected void afterListenerAdded(Listener<F> listener) {

    }

    protected void beforeListenerRemoved(com.daniel.listener.Listener<F> Listener) {

    }

    protected void afterListenerRemoved(Listener<F> listener) {
    }

    public boolean add(com.daniel.listener.Listener<F> Listener) {
        boolean result = false;
        if (!listeners.contains(Listener)) {
            beforeListenerAdded(Listener);
            result = this.listeners.add(Listener);
            afterListenerAdded(Listener);
        }
        return result;
    }


    public synchronized boolean remove(com.daniel.listener.Listener<F> Listener) {
        boolean result = false;
        synchronized (this)
        {
            if (listeners.contains(Listener)) {
                beforeListenerRemoved(Listener);
                result = this.listeners.remove(Listener);
                afterListenerRemoved(Listener);
            }
        }
        return result;
    }


    public synchronized void removeAll() {
        synchronized (this) {
            listeners.clear();
//            for (Listener listener : listeners) {
////                remove(listener);
//
//                if (listeners.contains(Listener)) {
//                    beforeListenerRemoved(Listener);
//                    result = this.listeners.remove(Listener);
//                    afterListenerRemoved(Listener);
//                }
//            }
////            int count = listeners.size();
////            for (int i = 0; i < count; i++) {
////                remove(listeners.get(i));
////            }
        }
    }


    public void callAll(F o) {
        synchronized (this) {
//            for (int i = 0; i < listeners.size(); i++) {
////                remove(listeners.get(i));
//                listeners.get(i).onCalled(this, o);
//            }


            for (Listener listener : listeners) {
                listener.onCalled(this, o);
            }
        }
    }
}
